<?php

namespace app\admin\controller\second;

use app\common\controller\Backend;
use think\Db;
/**
 * 二手房楼盘管理
 *
 * @icon fa fa-circle-o
 */
class Buildings extends Backend
{
    
    /**
     * Buildings模型对象
     * @var \app\admin\model\second\Buildings
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\second\Buildings;

    }
    

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage('andOr'); // 20200204 谢 对selectpage进行了改造，可以模糊搜索
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('building_name,alias_name1,alias_name2,id');
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 通过名称获取 id
     */
    public function getBuilding(){
        $name = $this->request->post('buildingName');
        $name = str_replace('小区','',$name);
        $likestr="building_name like '%" . $name . "%' OR alias_name1 like '%" . $name . "%' OR alias_name2 like '%" . $name . "%'";
        $list = (new \app\admin\model\second\Buildings())->where($likestr)->select();
        if(!empty($list)){
            return json(['success'=>true,'id'=>$list[0]->id]);
        }else
            return json(['success'=>false]);
    }
    /**
     * 获取小区名称
     */
    public function getAddress($ids){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        return json(['success'=>true,'address'=>$row->address,'areaName'=>$row->areaName,'areaCode'=>$row->areaCode,'metro_count'=>$row->metro_count,'business'=>$row->business]);
    }
  
    /**
     * 更新楼盘在售数量
     */
    public function updateCount($id){
        $model = new \app\admin\model\second\Items();
        $count = $model->where('building_id=' .$id)->count();
        $onsell= $model->where('building_id=' .$id . ' AND state=0')->count();
        $building = \app\admin\model\second\Buildings::get($id);
        if(!empty($building)){
            if($count==0){
                // $building->delete();
            }else{
                $building->second_count=$count;
                $building->second_onsell=$onsell;
                $building->save();
            }
        }

        // $sql = 'update mf_second_buildings  set second_count = (select count(*) from mf_second_items where mf_second_items.building_id =mf_second_buildings.id ),' .
        //     'second_onsell = (select count(*) from mf_second_items where mf_second_items.building_id =mf_second_buildings.id and state=0) where id='.$id;
        // Db::execute($sql);
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                // 判重
                $likestr="(building_name = '" . $params['building_name'] . "' OR alias_name1 = '" . $params['building_name'] . "' OR alias_name2 = '" . $params['building_name'] . "')";
                $count = (new \app\admin\model\second\Buildings())->where($likestr . " and areaName='" . $params['areaName'] . "'")->count();
                if($count>0){
                    $this->error('楼盘名称已经存在');
                }
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                // 判重
                // $count = (new \app\admin\model\second\Buildings())->where("id<>" . $ids . " and building_name='" . $params['building_name'] . "' and areaCode='" . $params['areaCode'] . "'")->count();
                // if($count>0){
                //     $this->error('楼盘名称已经存在');
                // }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    /// 合并到
                    if($params['merge']!=''){
                        $sql = 'UPDATE mf_second_items SET building_id=' . $params['merge']. ' WHERE building_id=' . $ids;
                        Db::execute($sql);
                        // 删除自己
                        $row->delete();
                        $this->updateCount($params['merge']);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if($row['latitude']=='' || $row['latitude']==null)$row['latitude']=31.866942;
        if($row['longitude']=='' || $row['longitude']==null)$row['longitude']=117.282699;
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    
                    // 如果有房源，禁止删除
                    if($v->second_count>0){

                    }else{
                        $count += $v->delete();
                    }
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
